<template>
  <div>
    <FormPanel ref="formPanel" :list="formList" :cols="3" :labelWidth="90" formType="add" :isSubmitBtn="false" @formChange="formChangeHandle" />
    <FilterTable
      ref="table"
      columnsRef="finance_repairFinance_receivables_reduction"
      height="auto"
      :columns="columns"
      :datakey="'rows'"
      :isSelectColumn="false"
      :onCellChange="changeCells"
      :onColumnsChange="columns => (this.columns = columns)"
    ></FilterTable>

    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'center'
      }"
    >
      <el-button type="primary" @click="saveDialog">确 定</el-button>
      <el-button @click="closeDialog(true)">取 消</el-button>
    </div>
  </div>
</template>

<script>
import moment from 'moment';
import { mapState } from 'vuex';
import { dictionary } from '@/utils/dictMixin';
import { addRole } from '@/api/common/auth/roleManage';
import { reduction } from '@/api/finance/repair/receivables';
import * as types from '@/api/common/auth/roleManage/types';
import { getUserId } from '@/assets/js/auth';
import { getAllUser } from '@/api/finance/advancesReceived/register';
import { isAuthorized } from '@/utils/index';
export default {
  name: 'Reduction',
  mixins: [dictionary],
  props: {
    type: {
      type: String,
      default: 'add'
    },
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    this.saveData = null;
    return {
      index: null,
      formList: this.createFormList(),
      columns: this.createTableColumns()
    };
  },
  computed: {
    ...mapState('app', ['btnLoading']),
    addBtnState() {
      return this.btnLoading[types.YAN_ROLE_ADD];
    }
  },
  mounted() {
    this.getEmployee(); // 经手人下拉
    this.formList.find(item => item.fieldName === 'derateDate').initialValue = moment().format('YYYY-MM-DD HH:mm:ss');
    this.formList.find(item => item.fieldName === 'handler').initialValue = getUserId();
    this.getAuth(); // 权限
  },
  methods: {
    getAuth() {
      // 维修收款可以负减免
      if (isAuthorized('1314', '13141011')) {
        this.formList.find(item => item.fieldName === 'derateAmount').min = -99999999;
      } else {
        this.formList.find(item => item.fieldName === 'derateAmount').min = 0;
      }
    },
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '收费对象代码',
          fieldName: 'PAYMENT_OBJECT_CODE',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '收费对象名称',
          fieldName: 'PAYMENT_OBJECT_NAME',
          disabled: true
        },
        {
          type: 'SELECT',
          itemList: [],
          label: '经手人',
          fieldName: 'handler',
          disabled: true
        },
        {
          type: 'DATE',
          dateType: 'datetime',
          label: '减免日期',
          fieldName: 'derateDate'
        },
        {
          type: 'INPUT_NUMBER',
          label: '减免金额',
          fieldName: 'derateAmount',
          precision: 2,
          min: 0,
          rules: [{ required: true, message: '请输入减免金额', trigger: 'change' }],
          change: val => {
            this.changeNum(val);
          }
        },
        {
          type: 'INPUT',
          label: '减免批准人',
          fieldName: 'derateRatifier',
          rules: [{ required: true, message: '请输入减免批准人', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '备注',
          fieldName: 'remark',
          selfCols: 2
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '结算单号',
          dataIndex: 'BALANCE_NO',
          sorter: true
        },
        {
          title: '车牌号',
          dataIndex: 'LICENSE',
          sorter: true
        },
        {
          title: '应收账款',
          dataIndex: 'RECEIVABLE_AMOUNT',
          precision: 2,
          sorter: true
        },
        {
          title: '已收账款',
          dataIndex: 'RECEIVED_AMOUNT',
          precision: 2,
          sorter: true
        },
        {
          title: '已免账款',
          dataIndex: 'DERATED_AMOUNT',
          precision: 2,
          sorter: true
        },
        {
          title: '未收账款',
          dataIndex: 'NOT_RECEIVED_AMOUNT',
          precision: 2,
          sorter: true
        },
        {
          title: '减免账款',
          dataIndex: 'DERATE_AMOUNT',
          precision: 2,
          sorter: true,
          editable: true,
          defaultEditable: true,
          editType: 'number',
          editRequired: true
        },
        {
          title: '是否结清',
          dataIndex: 'PAY_OFF',
          sorter: true,
          render: props => {
            return <span>{this.createDictText(props.row.BALANCE_CLOSE, '1004')}</span>;
          }
        }
      ];
    },
    openModel(data) {
      console.log('传入', data[0]);
      for (let [key, value] of Object.entries(data[0])) {
        this.formList.some(item => {
          if (item.fieldName === key) {
            item.initialValue = value;
            return true;
          }
        });
      }
      let sum = 0;
      for (let i = 0; i < data.length; i++) {
        data[i].DERATE_AMOUNT = (data[i].NOT_RECEIVED_AMOUNT - parseInt(data[i].NOT_RECEIVED_AMOUNT)).toFixed(2);
        sum += Number(data[i].DERATE_AMOUNT);
      }
      this.formList.find(item => item.fieldName === 'derateAmount').initialValue = sum.toFixed(2);
      this.$refs.table.$refs.pageTable.EXECUTE_INSERT(data);
      // this.getReductionRecord(data.BALA_PAYOBJ_ID, data.OWNER_CODE )
      // this.getReceiptsDetail(data.BALANCE_NO, data.OWNER_CODE )
    },
    changeNum(val) {
      if (this.$refs.table.$refs.pageTable.dataSource.length == 1) {
        this.$refs.table.$refs.pageTable.dataSource[0].DERATE_AMOUNT = val.toFixed(2);
      }
    },
    formChangeHandle(val) {
      this.saveData = val;
    },
    async getEmployee() {
      const res = await getAllUser();
      // console.log(res, '经手人');
      this.formList.find(item => item.fieldName === 'handler').itemList = res.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
    },
    // async saveDialog() {
    //   this.$refs.formPanel.SUBMIT_FORM();

    //   this.$set(this.saveData, 'dataType', '10461001')
    //   this.$set(this.saveData, 'dataSource', '10451001')
    //   if (this.saveData !== null) {
    //     const res = await addRole(this.saveData);
    //     if (res.resultCode === 200) {
    //       this.$notify.success({title: '提示信息',message:'新增成功!'});
    //       // 重新加载
    //       this.closeDialog('refresh');
    //     }else {
    //       this.$notify.error({title: '提示信息',message:res.errMsg||'新增失败!'});
    //       this.closeDialog()
    //     }
    //   }
    // },
    saveDialog() {
      this.$refs.formPanel.SUBMIT_FORM();
      // console.log('SUBMIT_FORM',this.$refs.formPanel.SUBMIT_FORM())
      if (this.saveData != null && !this.$refs.table.$refs.pageTable.GET_REQUIRED_ERROR()) {
        let tableData = _.cloneDeep(this.$refs.table.$refs.pageTable.dataSource);
        let sum = 0;
        for (const item of tableData) {
          sum += Number(item.DERATE_AMOUNT);
          if (item.DERATE_AMOUNT > item.NOT_RECEIVED_AMOUNT) {
            this.$notify.error({ title: '提示信息', message: '减免金额不能大于未收款金额' });
            flag = false;
            return;
          }
          if (Number(item.DERATE_AMOUNT) + item.DERATED_AMOUNT < 0) {
            this.$notify.error({ title: '提示信息', message: '减免账款与已免账款之和不能小于0!' });
            return;
          }
        }
        if (sum != this.saveData.derateAmount) {
          this.$notify.error({ title: '提示信息', message: '减免账款之和不相等!' });
          return;
        }
        this.$confirm('是否确认保存?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            let params = {
              ...this.saveData,
              paymentObjectList: this.$refs.table.$refs.pageTable.dataSource
            };
            // console.log("params",params)
            let res = await reduction(params);
            // console.log('res',res)
            if (res.resultCode == 200) {
              this.$notify.success({ title: '提示信息', message: '保存成功!' });
              this.closeDialog();
            }
          })
          .catch(() => {});
      } else {
        this.$notify.error({ title: '提示信息', message: '有必填项未填写!' });
      }
    },
    closeDialog(val) {
      this.$emit('close', val);
    },
    changeCells(keys, obj) {
      // console.log("keys",keys)
      // console.log("obj",obj)
      // console.log("table",this.$refs.table.$refs.pageTable.dataSource)
      /*  let key = Object.keys(keys)[0];
      let a = key.substring(key.indexOf('|') + 1);
      let data = this.$refs.table.$refs.pageTable.dataSource
      if (a == 'DERATE_AMOUNT') {
        let sum = 0
        for (let i = 0; i < data.length; i++) {
          sum += parseFloat(data[i].DERATE_AMOUNT);
        }
        this.formList.find(item => item.fieldName === 'derateAmount').initialValue = sum
      } */
      // console.log('changeCells',a,obj)
    }
  }
};
</script>

<style lang="less" scoped></style>
